package com.ycl.javacore.exam.limit;

import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TPSLimiter {

    private Semaphore semaphore = null;

    public TPSLimiter(int maxOps) {
        if (maxOps < 1) {
            throw new IllegalArgumentException("maxOps must be greater than zero");
        }
        this.semaphore = new Semaphore(maxOps);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() ->
                // 每秒释放给定数目的许可，将其返回到信号量
                semaphore.release(maxOps), 1000, 1000, TimeUnit.MILLISECONDS);
    }

    /**
     * 调用接口之前先调用此方法，当超过最大ops时该方法会阻塞
     */
    public void await() {
        semaphore.acquireUninterruptibly(1);
    }
}